package com.demo.paypalmanagement.controller.admin;

import com.alibaba.fastjson2.JSON;
import com.demo.paypalmanagement.common.BuildQuery;
import com.demo.paypalmanagement.model.entity.Message;
import com.demo.paypalmanagement.model.vo.MessageVO;
import com.demo.paypalmanagement.service.MessageService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/message/{userId}")
public class MessageController implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(MessageController.class);

    private static final Map<String, Session> userSessionMap = new ConcurrentHashMap<>();


    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        MessageController.applicationContext = applicationContext;
    }


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        log.info("WebSocket opened: " + session.getId());
        // 获取客户端的 IP 地址
        String clientIpAddress = getClientIpAddress(session);
        log.info("Client IP Address: " + clientIpAddress);
        userSessionMap.put(userId, session);
        //获取bean
        MessageService bean = applicationContext.getBean(MessageService.class);
        //设置查询条件
        MessageVO query = new MessageVO();
        query.setUserId(userId);
        // 查询数据
        List<Message> messageList = bean.list(BuildQuery.buildMssageWrapper(query));
        if (CollectionUtils.isEmpty(messageList)) {
            return;
        }
        this.read(query);
        sendMessage(userSessionMap.get(userId), JSON.toJSONString(messageList));
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        //转对象
        Message feedbackMessages = JSON.parseObject(message, Message.class);
        // 获取bean
        MessageService bean = applicationContext.getBean(MessageService.class);
        bean.save(feedbackMessages);
        //查询发送者消息
        MessageVO sendQuery = new MessageVO();
        sendQuery.setUserId(String.valueOf(feedbackMessages.getSenderId()));
        List<Message> entityList = bean.list(BuildQuery.buildMssageWrapper(sendQuery));
        sendMessage(userSessionMap.get(String.valueOf(feedbackMessages.getSenderId())),JSON.toJSONString(entityList));
        Session receiveSession = userSessionMap.get(String.valueOf(feedbackMessages.getReceiverId()));
        if (ObjectUtils.isEmpty(receiveSession)) {
            return;
        }
        MessageVO receiveQuery = new MessageVO();
        receiveQuery.setUserId(String.valueOf(feedbackMessages.getSenderId()));
        List<Message> receiveList =  bean.list(BuildQuery.buildMssageWrapper(receiveQuery));
        sendMessage(userSessionMap.get(String.valueOf(feedbackMessages.getReceiverId())),JSON.toJSONString(receiveList));

    }

    @OnClose
    public void onClose(Session session,@PathParam("userId") String userId) {
        userSessionMap.remove(userId);
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    private String getClientIpAddress(Session session) {
        String clientIpAddress = null;
        try {
            Map<String, Object> properties = session.getUserProperties();
            Object httpServletRequest = properties.get("javax.websocket.endpoint.remoteAddress");
            if (httpServletRequest instanceof String) {
                clientIpAddress = (String) httpServletRequest;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clientIpAddress;
    }
    private void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read(MessageVO vo) {
        MessageService bean = applicationContext.getBean(MessageService.class);
        // 查询出未读的消息修改成已读

        vo.setReceiverId(vo.getUserId());
        vo.setUserId(null);
        vo.setIsRead("0");
        List<Message> list = bean.list(BuildQuery.buildMssageWrapper(vo));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.forEach(
                item->item.setIsRead("1")
        );
        bean.updateBatchById(list);
    }
}
